// 这是一个简单的echo_udp
// server ->收消息->处理消息->发消息
//  ./tcp_server port
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cerr << "正确用法:" << argv[0] << " server_port" << endl;
        exit(-1);
    }
    string server_ip = "0.0.0.0";
    uint16_t server_port = stoi(argv[1]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cerr << "套接字创建失败" << endl;
    }
    cout << "套接字创建成功, sockfd:" << sockfd << endl;

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_port = htons(server_port);
    int bind_code = bind(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (bind_code < 0)
    {
        cerr << "绑定失败" << endl;
    }
    cout << "绑定成功" << endl;

    while (true)
    {
        char inbuffer[1024];
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        ssize_t n = recvfrom(sockfd, inbuffer, sizeof(inbuffer), 0, (struct sockaddr *)&client, &len);
        if (n > 0)
        {
            inbuffer[n] = '\0';
            cout << "send a request # " << inbuffer << endl;
            ssize_t m = sendto(sockfd, inbuffer, sizeof(inbuffer), 0, (struct sockaddr *)&client, len);
        }
    }

    return 0;
}